package fr.synchrone.starsudoku;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import fr.synchrone.starsudoku.provider.Players;

public class GameView extends Activity {
	 /** Called when the activity is first created. */
    private GamePart part;
    private TableLayout table;
    private TableRow rowValue;
    private TextView[][] allCases = new TextView[9][9] ;
    private int selectX;
    private int selectY;
    private int life;
    private TextView lifeView;
    private TextView timeView;
    private Timer timer;
	private long startTime;
	private Vibrator vibrator;
	private int correct;
	private int LEVEL_CASE = 20;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getIntent().getExtras();
        LEVEL_CASE = bundle.getInt("level");
        setContentView(R.layout.game);
        onNewGameStart();
    }
   
    @Override
    protected void onStop() {
    	super.onStop();
    	timer.cancel();
    }
	@Override
    protected void onDestroy() {
    	super.onDestroy();
    }
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.game_menu, menu); 
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch(id){
		case R.id.newGameItem:
			onNewGameStart();
			break;
		case R.id.endGameItem:
			goToMainPage();
			break;
		}
		return true;
	}
	
    private void initLifeView() {
		lifeView = (TextView) findViewById(R.id.lifeText);
		lifeView.setText("Life  : " + life);
	}

	private void initTimer() {
		if(startTime == 0L) {
			   startTime = System.currentTimeMillis();
			   timer = new Timer();
			   timer.schedule(new UpdateTimeTask(), 100, 200);
		}
	}
	private void onNewGameStart(){
		life = 4;
		startTime = 0L;
		correct = 0;
        part = new GamePart(LEVEL_CASE);
        table = (TableLayout) findViewById(R.id.mainTable);
        rowValue = (TableRow) findViewById(R.id.tableRow2);
        initLifeView();
        initGameView();
        initValueRow();
        initTimer();
	}
	private void initGameView(){
    	
    	for(int i = 0; i < 9; i++){
    		TableRow r = (TableRow)table.getChildAt(i);
    		for(int j = 0; j < 9; j++){
    			int	value = part.getGame()[i][j];
    			TextView textCase = (TextView) r.getChildAt(j);
    			allCases[i][j] = textCase;
    			final int x = i;
    			final int y = j;
				if(value != 0){
					textCase.setText("" + value);
				}
				else{
					textCase.setText("");
					textCase.setOnClickListener(new OnClickListener(){
						@Override
						public void onClick(View arg0) {
							allCases[selectX][selectY].setBackgroundResource(R.drawable.bak_case);
							allCases[selectX][selectY].setTextColor(0xffc1c1c1);
							selectX = x;
							selectY = y;
							allCases[x][y].setBackgroundResource(R.drawable.bak_case_select);
							allCases[x][y].setTextColor(0xff111111);
						}
					});
				}
			}
    	}
    }
    
    private void initValueRow(){
    	for(int i = 0; i < 9; i++){
    		final TextView textCase = (TextView) rowValue.getChildAt(i);
    		final int index = i;
    		textCase.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					if(part.validateCase(selectX, selectY, index+1)){
						if(part.getGame()[selectX][selectY] != index+1){
							correct ++;
						}
						part.getGame()[selectX][selectY] = index+1;
						allCases[selectX][selectY].setText(textCase.getText());
						if(correct == LEVEL_CASE){
							partSuccess();
						}
					}
					else{
						life --;
						if(life >= 0)
							lifeView.setText("Life  : " + life);
				        vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
						vibrator.vibrate(300);
					}
				}
    		});
    	}
    }

	private void partSuccess() {
    	timer.cancel();
		setContentView(R.layout.succes);
		initSuccessView();
	}
	 
    private void initSuccessView() {
		Button submit = (Button) findViewById(R.id.submitSuccesButton);
		submit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ContentValues values = new ContentValues();
				EditText et = (EditText)findViewById(R.id.succesNameTextField);
				values.put(Players.NAME, et.getText().toString());
				values.put(Players.CONNECTION_DATE, startTime);
				values.put(Players.PLAYED_TIME, System.currentTimeMillis() - startTime);
				getContentResolver().insert(Players.CONTENT_URI, values);
				goToMainPage();
			}
		});
	}
    
    private void goToMainPage(){
		Intent i = new Intent();
		i.setClass(GameView.this, StarSudoku.class);
        startActivity(i);
        finish();
    }
    
    class UpdateTimeTask extends TimerTask {
    	
	   public void run() {
		   timeView = (TextView) findViewById(R.id.timerText);
	       timeView.post(new Runnable() {
				@Override
				public void run() {
				       long millis = System.currentTimeMillis() - startTime;
				       int seconds = (int) (millis / 1000);
				       int minutes = seconds / 60;
				       seconds     = seconds % 60;
					   timeView.setText("Timer: " + String.format("%d:%02d", minutes, seconds));
				}
			});
	   }
    }
}
